<?php

namespace api\modules\v1\controllers;

use api\models\SignupForm;
use api\models\User;
use api\modules\v1\oauth2\Pdo;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use Yii;
use api\models\LoginForm;
use api\controllers\BaseController;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\helpers\ArrayHelper;
use yii\web\UnauthorizedHttpException;

class UserController extends BaseController
{
    public $modelClass = 'api\models\User';

    public function actions(){
        $actions = parent::actions();
        unset($actions['index'], $actions['delete'], $actions['create']);
        return $actions;
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),[
            'authenticator' => [
                'except' => ['signup','login','test'],  //免授权的方法
            ],
        ]);
    }

    public function actionTest(){

        Yii::error('This is a user test!!!','user');
        return Yii::t('app', 'Home');
    }

    /**
     * 注册用户.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post(),'') && $model->signup()) {
            return 'Thank you for registration. ';
        }else{
            $model->validate();
            return $model;
        }

    }

    /**
     * 用户登录.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post(),'') && $model->login()) {
            return $model->getAccessToken();
        } else {
            //登录不了的话，可能是status没有设置为10
            $model->validate();
            return $model;
        }
    }

    /**
     * 检查访问方法，判断访问令牌所有者是否为请求用户ID
     * @param string $action
     * @param null $model
     * @param array $params
     * @throws UnauthorizedHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        $oauthUser = Yii::$app->user->identity;

        if ($oauthUser['id'] != Yii::$app->request->get('id')) {
            throw new UnauthorizedHttpException(Yii::t('app/error', '30054'), $code = 30054);
        }
    }

}
